/**
 * FIFS - The Find It File System
 * Copyright (C) 2006 Chris Oklota (chris at oklota dot net)
 * 
 * This program is distributed under the terms of the GNU LGPL.
 * See the file http://www.gnu.org/licenses/lgpl.txt
 */
package fifs.plugin.mp3;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.farng.mp3.MP3File;
import org.farng.mp3.id3.ID3v1;
import org.farng.mp3.id3.ID3v2_2;

import fifs.plugin.FifsPlugin;

/**
 * This FIFS plugin will add tags to the MP3 file for artist and album
 */
public class FifsMp3Plugin extends FifsPlugin {

    /** The logger for this class */
    public static final Logger log = Logger.getLogger(FifsMp3Plugin.class);
    
    @Override
    public Set<String> getTags() {
        if (log.isTraceEnabled()) {
            log.trace("Getting ID3 tags from file " + path);
        }
        HashSet<String> tags = new HashSet<String>();
        try {
            File f = new File(path);
            MP3File mp3 = new MP3File(f);
            if (mp3.hasID3v1Tag()) {
                if (log.isTraceEnabled()) {
                    log.trace("Found ID3 v1 tag in file " + path);
                }
                ID3v1 id3 = mp3.getID3v1Tag();
                String album = id3.getAlbum();
                if ((album != null) && (album.trim().length() > 0)) {
                    tags.add(album.trim());
                }
                String artist = id3.getArtist();
                if ((artist != null) && (artist.trim().length() > 0)) {
                    tags.add(artist.trim());
                }
            } else if (mp3.hasID3v2Tag()) {
                if (log.isTraceEnabled()) {
                    log.trace("Found ID3 v2 tag in file " + path);
                }
                ID3v2_2 id3 = (ID3v2_2)mp3.getID3v2Tag();
                String album = id3.getAlbumTitle();
                if ((album != null) && (album.trim().length() > 0)) {
                    tags.add(album.trim());
                }
                String artist = id3.getAuthorComposer();
                if ((artist != null) && (artist.trim().length() > 0)) {
                    tags.add(artist.trim());
                }
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("No ID3 tags found in file " + path);
                }
            }
        } catch (Exception e) {
            log.error("Error parsing ID3 tags for MP3 file", e);
        }
        return tags;
    }

}
